import React, { useState, useEffect } from 'react'
import { Card, Button, Space, Modal, message, Tabs, Descriptions, Tag, Row, Col, Avatar } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined, FileTextOutlined, ExclamationCircleOutlined, UserOutlined, PhoneOutlined, MailOutlined } from '@ant-design/icons'
import DataTable from '../../../components/common/DataTable'
import Form from '../../../components/common/Form'
import { createResume, updateResume, getResume, listResumes, deleteResume, submitResume } from '../../../api/resume'

const { confirm } = Modal
const { TabPane } = Tabs

const Resume = () => {
    const [loading, setLoading] = useState(false)
    const [dataSource, setDataSource] = useState([])
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    })
    const [visible, setVisible] = useState(false)
    const [currentResume, setCurrentResume] = useState(null)
    const [viewVisible, setViewVisible] = useState(false)
    const [viewResume, setViewResume] = useState(null)

    // 模拟数据
    const mockResumes = [
        {
            id: 101,
            name: '张三',
            gender: '男',
            age: 28,
            phone: '13800138000',
            email: 'zhangsan@example.com',
            education: '本科',
            school: '北京大学',
            major: '计算机科学与技术',
            graduationYear: '2018',
            workExperience: '3年',
            lastCompany: 'ABC科技有限公司',
            lastPosition: '前端开发工程师',
            expectedPosition: '高级前端开发工程师',
            expectedSalary: '15k-20k',
            skills: 'HTML, CSS, JavaScript, React, Vue',
            status: '待筛选',
            source: '官网投递',
            applyDate: '2023-06-01',
            attachmentUrl: 'https://example.com/resume/101.pdf'
        },
        {
            id: 102,
            name: '李四',
            gender: '女',
            age: 26,
            phone: '13900139000',
            email: 'lisi@example.com',
            education: '硕士',
            school: '清华大学',
            major: '人力资源管理',
            graduationYear: '2020',
            workExperience: '1年',
            lastCompany: 'XYZ企业管理有限公司',
            lastPosition: 'HR助理',
            expectedPosition: '人力资源专员',
            expectedSalary: '8k-12k',
            skills: '招聘、培训、绩效考核、员工关系管理',
            status: '已筛选',
            source: '招聘网站',
            applyDate: '2023-06-05',
            attachmentUrl: 'https://example.com/resume/102.pdf'
        },
        {
            id: 103,
            name: '王五',
            gender: '男',
            age: 32,
            phone: '13700137000',
            email: 'wangwu@example.com',
            education: '本科',
            school: '上海交通大学',
            major: '市场营销',
            graduationYear: '2014',
            workExperience: '8年',
            lastCompany: '广州营销策划有限公司',
            lastPosition: '市场主管',
            expectedPosition: '市场营销经理',
            expectedSalary: '20k-25k',
            skills: '市场分析、品牌推广、活动策划、团队管理',
            status: '已面试',
            source: '内部推荐',
            applyDate: '2023-05-20',
            attachmentUrl: 'https://example.com/resume/103.pdf'
        }
    ]

    useEffect(() => {
        fetchResumes()
    }, [pagination.current, pagination.pageSize])

    // 获取简历数据
    const fetchResumes = async () => {
        setLoading(true)
        try {
            const params = {
                page: pagination.current,
                pageSize: pagination.pageSize
            }
            const res = await listResumes(params)
            setDataSource(res.data.items || [])
            setPagination({
                ...pagination,
                total: res.data.total || 0
            })
        } catch (error) {
            message.error('获取简历列表失败')
            console.error(error)
        } finally {
            setLoading(false)
        }
    }

    // 处理表格变化
    const handleTableChange = (pagination) => {
        setPagination(pagination)
    }

    // 处理搜索
    const handleSearch = async (value) => {
        setLoading(true)
        try {
            const params = {
                page: 1,
                pageSize: pagination.pageSize,
                keyword: value
            }
            const res = await listResumes(params)
            setDataSource(res.data.items || [])
            setPagination({
                ...pagination,
                current: 1,
                total: res.data.total || 0
            })
        } catch (error) {
            message.error('搜索失败')
            console.error(error)
        } finally {
            setLoading(false)
        }
    }

    // 添加简历
    const handleAdd = () => {
        setCurrentResume(null)
        setVisible(true)
    }

    // 编辑简历
    const handleEdit = (record) => {
        setCurrentResume(record)
        setVisible(true)
    }

    // 查看简历详情
    const handleView = async (id) => {
        try {
            const res = await getResume(id)
            setViewResume(res.data)
            setViewVisible(true)
        } catch (error) {
            message.error('获取简历详情失败')
            console.error(error)
        }
    }

    // 删除简历
    const handleDelete = (id) => {
        confirm({
            title: '确认删除',
            icon: <ExclamationCircleOutlined />,
            content: '确定要删除这份简历吗？此操作不可恢复。',
            onOk: async () => {
                try {
                    await deleteResume(id)
                    message.success('删除成功')
                    fetchResumes()
                } catch (error) {
                    message.error('删除失败')
                    console.error(error)
                }
            }
        })
    }

    // 表单提交
    const handleFormSubmit = async (values) => {
        try {
            if (currentResume) {
                // 编辑简历
                await updateResume(currentResume.id, values)
                message.success('编辑成功')
            } else {
                // 添加简历
                await createResume(values)
                message.success('添加成功')
            }
            setVisible(false)
            fetchResumes()
        } catch (error) {
            message.error(currentResume ? '编辑失败' : '添加失败')
            console.error(error)
        }
    }

    // 更新简历状态
    const handleStatusChange = (id, status) => {
        const newData = dataSource.map(item => {
            if (item.id === id) {
                return { ...item, status }
            }
            return item
        })
        setDataSource(newData)
        message.success(`状态已更新为：${status}`)
    }

    // 表格列定义
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: 80
        },
        {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
            render: (text, record) => (
                <a onClick={() => handleView(record)}>{text}</a>
            )
        },
        {
            title: '性别',
            dataIndex: 'gender',
            key: 'gender',
            width: 80
        },
        {
            title: '年龄',
            dataIndex: 'age',
            key: 'age',
            width: 80
        },
        {
            title: '学历',
            dataIndex: 'education',
            key: 'education'
        },
        {
            title: '期望职位',
            dataIndex: 'expectedPosition',
            key: 'expectedPosition'
        },
        {
            title: '工作经验',
            dataIndex: 'workExperience',
            key: 'workExperience'
        },
        {
            title: '期望薪资',
            dataIndex: 'expectedSalary',
            key: 'expectedSalary'
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status) => {
                let color = 'blue'
                if (status === '已筛选') color = 'green'
                if (status === '已面试') color = 'purple'
                if (status === '已录用') color = 'gold'
                if (status === '已拒绝') color = 'red'
                return <Tag color={color}>{status}</Tag>
            }
        },
        {
            title: '投递日期',
            dataIndex: 'applyDate',
            key: 'applyDate'
        },
        {
            title: '操作',
            key: 'action',
            width: 280,
            render: (_, record) => (
                <Space size="middle">
                    <Button 
                        type="text" 
                        icon={<EditOutlined />} 
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    <Button 
                        type="text" 
                        icon={<FileTextOutlined />} 
                        onClick={() => handleView(record)}
                    >
                        查看
                    </Button>
                    <Button 
                        type="text" 
                        danger 
                        icon={<DeleteOutlined />} 
                        onClick={() => handleDelete(record.id)}
                    >
                        删除
                    </Button>
                </Space>
            )
        }
    ]

    return (
        <div className="resume-container">
            <Card title="简历管理" extra={
                <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                    添加简历
                </Button>
            }>
                <DataTable 
                    columns={columns}
                    dataSource={dataSource}
                    loading={loading}
                    rowKey="id"
                    pagination={pagination}
                    onChange={handleTableChange}
                    onSearch={handleSearch}
                    onRefresh={fetchResumes}
                    searchPlaceholder="搜索姓名/电话/邮箱/职位/技能"
                />
            </Card>

            {/* 简历表单模态框 */}
            <Modal
                title={currentResume ? '编辑简历' : '添加简历'}
                open={visible}
                onCancel={() => setVisible(false)}
                footer={null}
                width={700}
            >
                <Form
                    initialValues={currentResume || {}}
                    onFinish={handleFormSubmit}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                >
                    <Tabs defaultActiveKey="1">
                        <TabPane tab="基本信息" key="1">
                            <Form.Item
                                name="name"
                                label="姓名"
                                rules={[{ required: true, message: '请输入姓名' }]}
                            >
                                <input placeholder="请输入姓名" />
                            </Form.Item>
                            <Form.Item
                                name="gender"
                                label="性别"
                                rules={[{ required: true, message: '请选择性别' }]}
                            >
                                <select>
                                    <option value="男">男</option>
                                    <option value="女">女</option>
                                </select>
                            </Form.Item>
                            <Form.Item
                                name="age"
                                label="年龄"
                                rules={[{ required: true, message: '请输入年龄' }]}
                            >
                                <input type="number" placeholder="请输入年龄" />
                            </Form.Item>
                            <Form.Item
                                name="phone"
                                label="电话"
                                rules={[{ required: true, message: '请输入电话' }]}
                            >
                                <input placeholder="请输入电话" />
                            </Form.Item>
                            <Form.Item
                                name="email"
                                label="邮箱"
                                rules={[{ required: true, message: '请输入邮箱' }]}
                            >
                                <input placeholder="请输入邮箱" />
                            </Form.Item>
                            <Form.Item
                                name="source"
                                label="来源"
                            >
                                <select>
                                    <option value="官网投递">官网投递</option>
                                    <option value="招聘网站">招聘网站</option>
                                    <option value="内部推荐">内部推荐</option>
                                    <option value="校园招聘">校园招聘</option>
                                    <option value="其他">其他</option>
                                </select>
                            </Form.Item>
                        </TabPane>
                        <TabPane tab="教育背景" key="2">
                            <Form.Item
                                name="education"
                                label="学历"
                                rules={[{ required: true, message: '请选择学历' }]}
                            >
                                <select>
                                    <option value="高中">高中</option>
                                    <option value="大专">大专</option>
                                    <option value="本科">本科</option>
                                    <option value="硕士">硕士</option>
                                    <option value="博士">博士</option>
                                </select>
                            </Form.Item>
                            <Form.Item
                                name="school"
                                label="学校"
                                rules={[{ required: true, message: '请输入学校' }]}
                            >
                                <input placeholder="请输入学校" />
                            </Form.Item>
                            <Form.Item
                                name="major"
                                label="专业"
                                rules={[{ required: true, message: '请输入专业' }]}
                            >
                                <input placeholder="请输入专业" />
                            </Form.Item>
                            <Form.Item
                                name="graduationYear"
                                label="毕业年份"
                                rules={[{ required: true, message: '请输入毕业年份' }]}
                            >
                                <input placeholder="请输入毕业年份" />
                            </Form.Item>
                        </TabPane>
                        <TabPane tab="工作经历" key="3">
                            <Form.Item
                                name="workExperience"
                                label="工作经验"
                                rules={[{ required: true, message: '请输入工作经验' }]}
                            >
                                <input placeholder="请输入工作经验，如：3年" />
                            </Form.Item>
                            <Form.Item
                                name="lastCompany"
                                label="上家公司"
                            >
                                <input placeholder="请输入上家公司" />
                            </Form.Item>
                            <Form.Item
                                name="lastPosition"
                                label="上家职位"
                            >
                                <input placeholder="请输入上家职位" />
                            </Form.Item>
                        </TabPane>
                        <TabPane tab="求职意向" key="4">
                            <Form.Item
                                name="expectedPosition"
                                label="期望职位"
                                rules={[{ required: true, message: '请输入期望职位' }]}
                            >
                                <input placeholder="请输入期望职位" />
                            </Form.Item>
                            <Form.Item
                                name="expectedSalary"
                                label="期望薪资"
                                rules={[{ required: true, message: '请输入期望薪资' }]}
                            >
                                <input placeholder="请输入期望薪资，如：10k-15k" />
                            </Form.Item>
                            <Form.Item
                                name="skills"
                                label="技能特长"
                                rules={[{ required: true, message: '请输入技能特长' }]}
                            >
                                <textarea placeholder="请输入技能特长，多个技能用逗号分隔" rows={4} />
                            </Form.Item>
                            <Form.Item
                                name="attachmentUrl"
                                label="简历附件"
                            >
                                <input placeholder="请输入简历附件URL" />
                            </Form.Item>
                        </TabPane>
                    </Tabs>
                </Form>
            </Modal>

            {/* 简历详情模态框 */}
            <Modal
                title="简历详情"
                open={viewVisible}
                onCancel={() => setViewVisible(false)}
                footer={[
                    <Button key="back" onClick={() => setViewVisible(false)}>
                        关闭
                    </Button>,
                    viewResume && viewResume.status !== '已录用' && (
                        <Button 
                            key="hire" 
                            type="primary" 
                            onClick={() => {
                                handleStatusChange(viewResume.id, '已录用')
                                setViewVisible(false)
                            }}
                        >
                            录用
                        </Button>
                    ),
                    viewResume && viewResume.status !== '已拒绝' && (
                        <Button 
                            key="reject" 
                            danger 
                            onClick={() => {
                                handleStatusChange(viewResume.id, '已拒绝')
                                setViewVisible(false)
                            }}
                        >
                            拒绝
                        </Button>
                    )
                ]}
                width={700}
            >
                {viewResume && (
                    <Tabs defaultActiveKey="1">
                        <TabPane tab="基本信息" key="1">
                            <div style={{ textAlign: 'center', marginBottom: 20 }}>
                                <Avatar size={64} icon={<UserOutlined />} />
                                <h2 style={{ marginTop: 8 }}>{viewResume.name}</h2>
                                <Space>
                                    <Tag color="blue">{viewResume.gender}</Tag>
                                    <Tag color="blue">{viewResume.age}岁</Tag>
                                    <Tag color="blue">{viewResume.education}</Tag>
                                    <Tag color="blue">{viewResume.workExperience}</Tag>
                                </Space>
                                <div style={{ marginTop: 8 }}>
                                    <Space>
                                        <PhoneOutlined /> {viewResume.phone}
                                        <MailOutlined /> {viewResume.email}
                                    </Space>
                                </div>
                            </div>
                            <Descriptions bordered column={2}>
                                <Descriptions.Item label="ID">{viewResume.id}</Descriptions.Item>
                                <Descriptions.Item label="投递日期">{viewResume.applyDate}</Descriptions.Item>
                                <Descriptions.Item label="简历来源">{viewResume.source}</Descriptions.Item>
                                <Descriptions.Item label="状态">
                                    <Tag color={
                                        viewResume.status === '已筛选' ? 'green' :
                                        viewResume.status === '已面试' ? 'purple' :
                                        viewResume.status === '已录用' ? 'gold' :
                                        viewResume.status === '已拒绝' ? 'red' : 'blue'
                                    }>
                                        {viewResume.status}
                                    </Tag>
                                </Descriptions.Item>
                            </Descriptions>
                        </TabPane>
                        <TabPane tab="教育背景" key="2">
                            <Descriptions bordered column={1}>
                                <Descriptions.Item label="学历">{viewResume.education}</Descriptions.Item>
                                <Descriptions.Item label="学校">{viewResume.school}</Descriptions.Item>
                                <Descriptions.Item label="专业">{viewResume.major}</Descriptions.Item>
                                <Descriptions.Item label="毕业年份">{viewResume.graduationYear}</Descriptions.Item>
                            </Descriptions>
                        </TabPane>
                        <TabPane tab="工作经历" key="3">
                            <Descriptions bordered column={1}>
                                <Descriptions.Item label="工作经验">{viewResume.workExperience}</Descriptions.Item>
                                <Descriptions.Item label="上家公司">{viewResume.lastCompany}</Descriptions.Item>
                                <Descriptions.Item label="上家职位">{viewResume.lastPosition}</Descriptions.Item>
                            </Descriptions>
                        </TabPane>
                        <TabPane tab="求职意向" key="4">
                            <Descriptions bordered column={1}>
                                <Descriptions.Item label="期望职位">{viewResume.expectedPosition}</Descriptions.Item>
                                <Descriptions.Item label="期望薪资">{viewResume.expectedSalary}</Descriptions.Item>
                                <Descriptions.Item label="技能特长">
                                    {viewResume.skills.split(',').map((skill, index) => (
                                        <Tag key={index} color="blue" style={{ margin: '2px' }}>{skill.trim()}</Tag>
                                    ))}
                                </Descriptions.Item>
                                {viewResume.attachmentUrl && (
                                    <Descriptions.Item label="简历附件">
                                        <a href={viewResume.attachmentUrl} target="_blank" rel="noopener noreferrer">
                                            查看简历附件
                                        </a>
                                    </Descriptions.Item>
                                )}
                            </Descriptions>
                        </TabPane>
                        <TabPane tab="状态管理" key="5">
                            <div style={{ padding: '20px 0' }}>
                                <h3>更新简历状态</h3>
                                <Space style={{ marginTop: 16 }}>
                                    <Button 
                                        type={viewResume.status === '待筛选' ? 'primary' : 'default'}
                                        onClick={() => handleStatusChange(viewResume.id, '待筛选')}
                                    >
                                        待筛选
                                    </Button>
                                    <Button 
                                        type={viewResume.status === '已筛选' ? 'primary' : 'default'}
                                        onClick={() => handleStatusChange(viewResume.id, '已筛选')}
                                    >
                                        已筛选
                                    </Button>
                                    <Button 
                                        type={viewResume.status === '已面试' ? 'primary' : 'default'}
                                        onClick={() => handleStatusChange(viewResume.id, '已面试')}
                                    >
                                        已面试
                                    </Button>
                                    <Button 
                                        type={viewResume.status === '已录用' ? 'primary' : 'default'}
                                        onClick={() => handleStatusChange(viewResume.id, '已录用')}
                                    >
                                        已录用
                                    </Button>
                                    <Button 
                                        danger
                                        type={viewResume.status === '已拒绝' ? 'primary' : 'default'}
                                        onClick={() => handleStatusChange(viewResume.id, '已拒绝')}
                                    >
                                        已拒绝
                                    </Button>
                                </Space>
                            </div>
                        </TabPane>
                    </Tabs>
                )}
            </Modal>
        </div>
    )
}

export default Resume